package com.hsmw.api.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hsmw.api.config.jwt.CurrentHsmwUserUtils;
import com.hsmw.api.config.jwt.JwtTokenUtils;
import com.hsmw.api.config.jwt.LoginUser;
import com.htn.common.core.util.ErrorCodeUtil;
import com.hsmw.api.controller.pub.RedisCache;
import com.hsmw.api.service.*;
import com.htn.common.core.domain.WxLoginVO;
import com.hsmw.common.util.ValidateCodeUtil;
import com.htn.common.core.base.BusinessType;
import com.htn.common.core.base.DataResponse;
import com.hsmw.common.base.Log;
import com.htn.common.core.constant.CommonConstants;
import com.htn.common.core.constant.UserTypeEnum;
import com.hsmw.api.utils.CommonUtils;
import com.htn.common.core.utils.StringUtils;
import com.hsmw.domain.HsmwConcreteUser;
import com.hsmw.domain.HsmwItem;
import com.hsmw.domain.HsmwPmUser;
import com.hsmw.domain.HsmwTpspUser;
import com.hsmw.domain.vo.LoginRequestVO;
import com.tencentyun.TLSSigAPIv2;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.spec.InvalidParameterSpecException;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.htn.common.core.constant.CommonConstants.ResponseStatus.SUCCESS;

/**
 * @author WD
 * @description 认证授权
 **/
@RestController
@RequestMapping("/api/auth")
@Api(tags = "API-认证模块")
@Slf4j
public class AuthController {

	@Autowired
	private AuthService authService;
	@Autowired
	private StringRedisTemplate stringRedisTemplate;
	@Autowired
	private CurrentHsmwUserUtils currentHsmwUserUtils;

	@Autowired
	private RedisCache redisCache;


	@Autowired
	private HsmwItemService hsmwItemService;




	@Autowired
	private HsmwPmUserService hsmwPmUserService;

	@Autowired
	private HsmwConcreteUserService hsmwConcreteUserService;

	@Autowired
	private HsmwDriverUserService hsmwDriverUserService;

	@Autowired
	private HsmwBizUserService hsmwBizUserService;

	@Autowired
	private HsmwHtnUserService hsmwHtnUserService;

	@Autowired
	private HsmwTpspUserService hsmwTpspUserService;

	@Autowired
	private HsmwSaleUserService hsmwSaleUserService;


	@Value(value = "${tcloud.sdkappid}")
	private Long sdkappid;

	@Value(value = "${tcloud.sdkKey}")
	private String sdkKey;

	private static List headPicHub =new ArrayList();



	@PostMapping("/login")
	@ApiOperation("登录  账号类型  BIZ  中控；HTN 混天凝平台账号；DRIVER 司机；PM 项目经理；CONCRETE  搅拌站；SALE：销售；TPSP 第三方服务商")
	public DataResponse login(LoginRequestVO loginRequestVo) {
		if(StringUtils.isBlank(loginRequestVo.getUsername())){
			return  DataResponse.failure(ErrorCodeUtil.E_220,"用户名为空，请重新输入！");
		}
		if(StringUtils.isBlank(loginRequestVo.getType())){
			return  DataResponse.failure(ErrorCodeUtil.E_220,"账号类型为空，请重新输入！");
		}
		return authService.getToken(loginRequestVo);
	}

	@Log(title = "司机端：登出", businessType = BusinessType.QUERY)
	@PostMapping("/logout")
	@ApiOperation("退出")
	public DataResponse logout() {
		authService.deleteTokenFromRedis();
		return new DataResponse(SUCCESS);
	}

	@PostMapping("/getHsmwUser")
	@ApiOperation("获取当前登陆用户的详细信息")
	public DataResponse getHsmwUser() {
		return new DataResponse(SUCCESS, currentHsmwUserUtils.getCurrentUserInfo());
	}

	@PostMapping("/getHsmwUserAdvice")
	@ApiOperation("获取当前登陆用户的详细信息Adcice")
	public LoginUser getHsmwUserAdvice() {
		return currentHsmwUserUtils.getCurrentUserInfo();
	}


//	@Async("orderScheduledTaskExecutor")
	@GetMapping("/verifyCode")
	@ApiOperation(value = "图片验证码")
	public DataResponse getCaptchaBase64(HttpServletResponse response) {
		JSONObject jsonObject = new JSONObject();
		try {
			response.setContentType("image/png");
			response.setHeader("Cache-Control", "no-cache");
			response.setHeader("Expire", "0");
			response.setHeader("Pragma", "no-cache");
			String uuid = UUID.randomUUID().toString();
			Map<String, String> codeMap = ValidateCodeUtil.getRandomCodeBase64();
			jsonObject.put("url", "data:image/png;base64," + codeMap.get("base64String"));
			jsonObject.put("captchaId", uuid);
			// 将验证码存入redis里面
			stringRedisTemplate.opsForValue().set(uuid, codeMap.get("code"), 1, TimeUnit.MINUTES);
		} catch (Exception e) {
		}
		return new DataResponse(SUCCESS, jsonObject);
	}


	/**
	 * IM userSign生成接口
	 *
	 * @return 用户信息
	 * */
	@ApiOperation("IM userSign生成接口")
	@PostMapping("generateUserSign")
	public DataResponse generateUserSign(String userId){
		System.out.println("generateUserSign传的参数为 userId==="+userId);
		if(StringUtils.isBlank(userId)){
			return  DataResponse.failure(CommonConstants.ResponseStatus.VALIDATE_FAILED.getCode(),"您输入的用户ID为空，请重新输入！ ");
		}
		TLSSigAPIv2 tlsSigAPIv2 = new TLSSigAPIv2(sdkappid,sdkKey);
		String  userSign = tlsSigAPIv2.genUserSig(userId,3600*24*365);
		return  new DataResponse().success(userSign);
	}





}
